package com.ttg.web.service.job.impl;

import com.google.common.collect.Lists;
import com.google.common.util.concurrent.ListenableFuture;
import com.ttg.common.annotation.TaskRunMethod;
import com.ttg.common.enums.DimTypeEnum;
import com.ttg.common.exception.BaseException;
import com.ttg.common.vo.TaskResultVO;
import com.ttg.model.dto.QualityManageReportDTO;
import com.ttg.common.dto.TaskBaseDTO;
import com.ttg.model.dto.job.MerchScoreDTO;
import com.ttg.model.pojo.ModelMctMonth;
import com.ttg.model.pojo.QualityManageMerchReport;
import com.ttg.model.pojo.QualityManageTypeRule;
import com.ttg.web.dao.*;
import com.ttg.web.juc.TasktemplateHelper;
import com.ttg.web.service.job.MerchClassificationJobService;
import com.ttg.web.service.job.QualityManageCommon;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Description：
 * Author: chenyou
 * Date: 2025/9/2 14:09
 * Company: ttg
 * Copyright: Copyright (c) 2025
 */
@Slf4j
@Service
@TaskRunMethod(value = "merchClassificationTask")
public class MerchClassificationJobServiceImpl extends QualityManageCommon implements MerchClassificationJobService {

    @Value("${tlinx.isJuc:false}")
    private volatile Boolean isJuc;//是否启用异步回调
    @Autowired
    private TasktemplateHelper tasktemplateHelper;
    @Autowired
    private QualityManageMerchReportDao merchReportDao;
    @Autowired
    private QualityManageWeightConfigDao weightConfigDao;
    @Autowired
    private QualityManageTypeRuleDao typeRuleDao;

    @Override
    public TaskResultVO merchClassification(TaskBaseDTO reqDto) {
        reqDto = getCheckYearAndMonth(reqDto);
        List<String> mctNoList = merchReportDao.getMctNoList(reqDto.getYear(), reqDto.getMonth());
        List<Long> mctNoList1 = mctNoList.stream().map(o -> Long.parseLong(o)).collect(Collectors.toList());

        List<List<Long>> mctNoPartList = Lists.partition(mctNoList1,500);
        List<ListenableFuture<TaskResultVO>> futures = new ArrayList<>();
        List<TaskResultVO> results = new ArrayList<>();

        List<QualityManageTypeRule> rules = typeRuleDao.getByDimType(DimTypeEnum.商户维度.getValue());
        if(rules==null){
            throw new BaseException("商户质量分类规则不能为空");
        }
        for(List<Long> mctNoPart : mctNoPartList){
            MerchScoreDTO merchScoreDTO = new MerchScoreDTO();
            merchScoreDTO.setMctNos(mctNoPart);
            merchScoreDTO.setTypeRules(rules);
            if(isJuc){
                futures.add(tasktemplateHelper.submit(this,reqDto,merchScoreDTO));
            }else {
                TaskResultVO result = merchClassificationTask(reqDto,merchScoreDTO);
                results.add(result);
            }
        }

        return taskResult(results,futures,isJuc);
    }

    /**
     * 可异步处理的逻辑
     */
    public TaskResultVO merchClassificationTask(TaskBaseDTO reqDto, MerchScoreDTO merchScoreDTO){
        try {
            List<Long> mctNos = merchScoreDTO.getMctNos();

            List<QualityManageMerchReport> reports = new ArrayList<>();
            for(Long mctNo : mctNos) {
                List<QualityManageTypeRule> rules = merchScoreDTO.getTypeRules();
                //1. 获取行业质量报告,活跃率得分,清算成本得分,存款归集得分,加权得分
                QualityManageMerchReport report = merchReportDao.getByUnique(reqDto.getYear(), reqDto.getMonth(), String.valueOf(mctNo));

                QualityManageReportDTO reportDTO = new QualityManageReportDTO();
                reportDTO.setRepWeightScore(report.getRepWeightScore());
                reportDTO.setRepLivenessScore(report.getRepLivenessScore());
                reportDTO.setRepClearCostScore(report.getRepClearCostScore());
                reportDTO.setRepAvgScore(report.getRepAvgScore());

                Long qtrId = calculateQtrId(reportDTO, rules);
                if(qtrId==null){
                    report.setRepQtrId(0L);
                    report.setRepRemark("跑批年月："+reqDto.getYear() + reqDto.getMonth()+",商户号："+mctNo+"，计算分类错误,无法匹配分类");
                }else {
                    report.setRepQtrId(qtrId);
                }

                reports.add(report);
            }
            merchReportDao.efficientBatchSaveOrUpdate(reports);
        }catch (BaseException e) {
            e.printStackTrace();
            return taskReuslt(Status.FAIL.getValue(),false, e.getMsg());
        }catch (Exception ex){
            ex.printStackTrace();
            String exType = ex.getClass().getSimpleName();
            return taskReuslt(Status.FAIL.getValue(),false,"异常类型：" + exType + ",异常信息：" + ex.getMessage());
        }
        return taskReuslt(Status.SUCCESS.getValue(),false,"ok");
    }
}
